package rc.workflow.WorkflowHistory;

/**
 * Created by IntelliJ IDEA.
 * User: Slejus
 * Date: 13.6.11
 * Time: 13.32
 * To change this template use File | Settings | File Templates.
 */

import org.alfresco.repo.web.scripts.workflow.AbstractWorkflowWebscript;
import org.alfresco.repo.web.scripts.workflow.WorkflowModelBuilder;
import org.alfresco.service.cmr.repository.NodeRef;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;

import java.util.*;

public class WorkflowHistoryWebScript extends AbstractWorkflowWebscript {

    public static final String PARAM_STORE_TYPE = "store_type";
    public static final String PARAM_STORE_ID = "store_id";
    public static final String PARAM_NODE_ID = "id";

    @Override
    protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache) {
        Map<String, String> params = req.getServiceMatch().getTemplateVars();

        // get nodeRef from request
        NodeRef nodeRef = new NodeRef(params.get(PARAM_STORE_TYPE), params.get(PARAM_STORE_ID), params.get(PARAM_NODE_ID));

        // list of all active workflows for nodeRef
        /* List<WorkflowInstance> workflows = workflowService.getWorkflowsForContent(nodeRef, true);

        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(workflows.size());

        for (WorkflowInstance workflow : workflows)
        {
            results.add(modelBuilder.buildSimple(workflow));
        }
        */

        // list of all inactive (completed) workflows for nodeRef
        List<org.alfresco.service.cmr.workflow.WorkflowInstance> workflowsHistory = workflowService.getWorkflowsForContent(nodeRef, false);
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(workflowsHistory.size());

        // Sorting by endDate
        Collections.sort(workflowsHistory, new CustomComparator());

        for (org.alfresco.service.cmr.workflow.WorkflowInstance workflowHis : workflowsHistory) {
            //System.out.println("WORKFLOW---STARTDATE: " + workflowHis.startDate.toString());
            results.add(modelBuilder.buildSimple(workflowHis));
        }

        Map<String, Object> model = new HashMap<String, Object>();

        // build the model for ftl
        model.put("workflowInstances", results);
        return model;
    }
}

class CustomComparator implements Comparator<org.alfresco.service.cmr.workflow.WorkflowInstance> {
    @Override
    public int compare(org.alfresco.service.cmr.workflow.WorkflowInstance o1, org.alfresco.service.cmr.workflow.WorkflowInstance o2) {
        return o1.getEndDate().compareTo(o2.getEndDate());
    }
}
